package fr.upmf.miam.imageannotation;

import fr.upmf.miam.imageannotation.ImageAnnotationProvider.C;
import java.util.ArrayList;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.SparseBooleanArray;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;

public class ListContactsActivity extends Activity implements OnClickListener {
    Button button;
    ListView listView;
    ArrayAdapter<String> adapter;
    
    ArrayList<Integer> peopleIds = new ArrayList<Integer>();
    String idImg;
    

    protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.activity_list_contact);
	
	listView = (ListView) findViewById(R.id.list);
	button = (Button) findViewById(R.id.testbutton);
	idImg = this.getIntent().getData().getPathSegments().get(1);
	
	//contacts du tel
    	Cursor people = getContentResolver().query(
    		Uri.withAppendedPath(C.People.CONTENT_URI, "S"),
    		null,
    		C.Annotation.PICTURE_ID + "=?", new String[] { idImg }, null);
    		
    	//initialise le tableau de contact à afficher + la liste des contacts de l'image (cases à cocher)
    	int i = 0;
    	String[] contacts = new String[people.getCount()];
    	ArrayList<Integer> checked = new ArrayList<Integer>();
	while (people.moveToNext()) {
	    contacts[i] = people.getString(people.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
	    peopleIds.add((int) people.getLong(people.getColumnIndex(ContactsContract.Contacts._ID)));
	    
	    if(people.getString(people.getColumnIndex(C.People.URI))!=null) {    
		checked.add(i);
	    }
	    i++;
	}
	
	//affichage
	adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice, contacts);
	listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
	listView.setAdapter(adapter);
	for(Integer j : checked) {
	    listView.setItemChecked (j, true);
	}
	
	button.setOnClickListener(this);
    }

    public void onClick(View v) {
	
	//liste de contacts selectionnes et non selectionnes
	ArrayList<Integer> in = new ArrayList<Integer>();
	ArrayList<Integer> out = new ArrayList<Integer>();
	SparseBooleanArray list = listView.getCheckedItemPositions();
	for (int i = 0; i < list.size(); i++) {
	    if (list.valueAt(i)) {
		in.add(peopleIds.get(list.keyAt(i)));
	    } else {
		out.add(peopleIds.get(list.keyAt(i)));
	    }
	}

	//contacts selectionnes
	for(Integer i : in) {
	    
	    //on enregistre le contact en BD s'il n'existe pas deja
	    ContentValues cv = new ContentValues();
	    cv.put(ImageAnnotationContract.People.URI, Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_URI, i+"").toString());
	    Uri uriContact = getContentResolver().insert(ImageAnnotationContract.People.CONTENT_URI, cv);

	    //on lie le contact à l'image si ce n'est pas deja fait
	    String idPeople = uriContact.getPathSegments().get(1);
	    
	    Cursor linked = getContentResolver().query(
		    Uri.withAppendedPath(C.People.CONTENT_URI, idPeople + "/picture"),
		    new String[] { C.Annotation.PEOPLE_ID },
		    C.Annotation.PICTURE_ID + "=? AND " + C.Annotation.PEOPLE_ID + "=?", new String[] { idImg, idPeople }, 
		    null
	    );
	    if(linked.getCount()==0) {
	    
    	    	ContentValues cv2 = new ContentValues();
    	    	cv2.put(ImageAnnotationContract.Annotation.PEOPLE_ID, idPeople);
    	    	cv2.put(ImageAnnotationContract.Annotation.PICTURE_ID , idImg);
    	    
    	    	Uri uriImgId = Uri.withAppendedPath(ImageAnnotationContract.People.CONTENT_URI, idPeople + "/picture");
    	    	getContentResolver().insert(uriImgId, cv2);
	    }
	}
	
	//contacts non selectionnes
	for(Integer j : out) {
	    
	    //test si le contact existe
	    Cursor people = getContentResolver().query(
		    ImageAnnotationContract.People.CONTENT_URI, 
		    new String[] { C.People._ID },
		    C.People.URI + "=?", new String[] { Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_URI, j+"").toString() }, 
		    null
	    );
	    if(people.getCount()==0) { break; }
	    people.moveToFirst();
	    String idPeople = people.getString(people.getColumnIndex(C.People._ID));
	    
	    //test si l'annotation existe
	    Cursor linked = getContentResolver().query(
		    Uri.withAppendedPath(C.People.CONTENT_URI, idPeople + "/picture"),
		    new String[] { C.Annotation.PEOPLE_ID },
		    C.Annotation.PICTURE_ID + "=? AND " + C.Annotation.PEOPLE_ID + "=?", new String[] { idImg, idPeople }, 
		    null
	    );
	    if(linked.getCount()==0) { break; }
	    
	    //suppression de l'annotation
	    getContentResolver().delete(
		    Uri.withAppendedPath(ImageAnnotationContract.People.CONTENT_URI, idPeople + "/picture"), 
		    C.Annotation.PICTURE_ID + "=? AND " + C.Annotation.PEOPLE_ID + "=?", new String[] { idImg, idPeople }
	   );
	}
	
	//renvoie vers l'image
	Intent intent = new Intent();
	intent.setAction(Intent.ACTION_EDIT);
	Uri imgUriPicture = Uri.withAppendedPath(ImageAnnotationContract.Picture.CONTENT_URI, idImg);
	intent.setDataAndType(imgUriPicture, "image/*");
	startActivity(intent);
    }
}